import { Button, Col, Form, Input, message, Row, Select, Space } from 'antd';
import { useEffect } from 'react';

import personalInfoService from '@/api/services/stars/personalInfo';
import Card from '@/components/card';
import { UploadAvatar } from '@/components/upload';
import { datetime } from '@/utils/format-date';

import { UserInfo } from '#/entity';

const { getPersonalInfo } = personalInfoService;

export default function GeneralTab() {
  const [form] = Form.useForm();

  // 请求个人信息
  // 监听数据变化，更新表单值
  useEffect(() => {
    getPersonalInfo().then((data) => {
      form.setFieldsValue({
        code: data.code,
        name: data.name,
        gender: data.gender,
        email: data.email,
        mobile: data.mobile,
        status: data.status,
        createAt: data.createAt,
        roles: data.roles,
        portrait: data.portrait,
      });
    });
  }, [form]);
  const handleAvatarSuccess = (success: string) => {
    // 可以在这里更新用户信息或刷新数据
    form.setFieldsValue({ portrait: success });
    onClickSave();
  };
  const portrait = Form.useWatch('portrait', form);

  const onClickSave = () => {
    form
      .validateFields()
      .then((value) => {
        const transData = {
          gender: value.gender,
          name: value.name,
          portrait: value.portrait,
          email: value.email,
          mobile: value.mobile,
        };
        personalInfoService.updateInfo(transData).then(async (res) => {
          if (res) {
            message.success('保存成功');
          }
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };
  return (
    <Row gutter={[16, 16]}>
      <Col span={24} lg={8}>
        <Card className="flex-col !px-6 !pb-10 !pt-20">
          <Form form={form}>
            <Form.Item name="portrait">
              <UploadAvatar defaultAvatar={portrait} onUploadSuccess={handleAvatarSuccess} />
            </Form.Item>
            <Space className="py-6">
              <Form.Item<UserInfo>
                label="名字"
                name="name"
                rules={[
                  { required: true, message: '请输入名字' },
                  { min: 2, max: 20, message: '名字长度在2-20位之间' },
                ]}
              >
                <Input />
              </Form.Item>
            </Space>
          </Form>
        </Card>
      </Col>
      <Col span={24} lg={16}>
        <Card>
          <Form layout="vertical" form={form} labelCol={{ span: 8 }} className="w-full">
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item<UserInfo>
                  label="账户"
                  name="code"
                  rules={[
                    { required: true, message: '请输入账户' },
                    { min: 3, message: '账户长度不能小于3位' },
                  ]}
                >
                  <Input disabled />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item<UserInfo>
                  label="性别"
                  name="gender"
                  rules={[{ required: true, message: '请选择性别' }]}
                  normalize={(value) => {
                    if (!value || (value !== 'MALE' && value !== 'FEMALE')) {
                      return 'unknown';
                    }
                    return value;
                  }}
                >
                  <Select>
                    <Select.Option value="MALE">男</Select.Option>
                    <Select.Option value="FEMALE">女</Select.Option>
                    <Select.Option value="UN_KNOW">未知</Select.Option>
                  </Select>
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item<UserInfo>
                  label="邮箱"
                  name="email"
                  rules={[{ type: 'email', message: '请输入正确的邮箱格式' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item<UserInfo>
                  label="电话"
                  name="mobile"
                  rules={[
                    {
                      validator: async (_, value) => {
                        if (!value) {
                          return Promise.resolve();
                        }
                        const pattern = /^1[3-9]\d{9}$/;
                        if (!pattern.test(value)) {
                          return Promise.reject(new Error('请输入正确的手机号格式'));
                        }
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12}>
                <Form.Item<UserInfo>
                  label="状态"
                  name="status"
                  getValueProps={(value) => {
                    let displayValue = value;
                    if (value === 'ENABLE') {
                      displayValue = '启用';
                    } else if (value === 'DISABLE') {
                      displayValue = '禁用';
                    }
                    return { value: displayValue };
                  }}
                >
                  <Input disabled />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item<UserInfo>
                  label="创建时间"
                  name="createAt"
                  getValueProps={(value) => ({
                    value: datetime(value),
                  })}
                >
                  <Input disabled />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item<UserInfo>
                  label="角色"
                  name="roles"
                  getValueProps={(value) => ({
                    value: Array.isArray(value) ? value.map((role) => role.name).join(',') : '',
                  })}
                >
                  <Input disabled />
                </Form.Item>
              </Col>
            </Row>

            <div className="flex w-full justify-end">
              <Button type="primary" onClick={onClickSave}>
                保存
              </Button>
            </div>
          </Form>
        </Card>
      </Col>
    </Row>
  );
}
